package org.alex.nettychat.netty.first.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;


/**
 * 服务端处理客户数据
 *
 * @author : alex
 */
public class FirstServerHandler extends ChannelInboundHandlerAdapter {

    /**
     * 接收到客户端发来的数据之后被回调
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;

        // 接受到客户端消息
        System.out.println(LocalDateTime.now() + ":服务端读取到的数据->" + byteBuf.toString(StandardCharsets.UTF_8));

        // 返回数据到客户端
        ctx.channel().writeAndFlush(getByteBuff(ctx));
    }

    private ByteBuf getByteBuff(ChannelHandlerContext ctx) {
        // 1 获取二进制ByteBuf
        ByteBuf buffer = ctx.alloc().buffer();
        // 2 准备数据，指定字符集为UTF-8
        byte[] bytes = "服务端已收到消息!".getBytes(StandardCharsets.UTF_8);
        // 3 填充数据到ByteBuf
        buffer.writeBytes(bytes);

        return buffer;
    }
}
